//
//  VCAccount.swift
//  AirlineReservation
//
//  Created by Kevin on 2020/1/27.
//  Copyright © 2020 Kevin. All rights reserved.
//

import UIKit

public protocol VCAccountDelete {
    func returnAccount(bean:AccountBean)
}

class VCAccount: VCBase {
    
    private lazy var accountView:AccountView = {
        let ui = AccountView()
        let uiY = backroundWhite.frame.maxY + MARGIN10
        ui.frame = CGRect(x: 0, y: uiY, width: SCREEN_WIDTH, height: SCREEN_HEIGHT)
        return ui
    }()
    
    public var delegate:VCAccountDelete?
    public var isNeedAccount: Bool = false
    public var tempLinkman:[AccountBean]?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        init_view()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        init_data()
        init_event()
    }
}

extension VCAccount {
    
    private func init_event() -> Void {
        // 圆加号点击
        cirleAddView.complete = {
            self.pushVc(title: "添加联系人", vc: VCAccountManger())
        }
        
        // 背景点击
        accountView.completeBackground = {user in
            if self.isNeedAccount {
                self.delegate?.returnAccount(bean: user)
                self.navigationController?.popViewController(animated: true)
            }
        }
        
        // 编辑点击
        accountView.complete = {item in
            let vc = VCAccountManger()
            vc.isShowDelete = true
            vc.isEditAllInfo = true
            vc.account = self.tempLinkman?[item]
            self.pushVc(title: "编辑联系人", vc: vc)
        }
    }
    
    func getOrder(str:String) -> AccountBean? {
        let order1Data = str.data(using: .utf8)
        guard let dict = try? (JSONSerialization.jsonObject(with: order1Data!, options: .mutableContainers) as! NSDictionary) else {
            print("order1 convert error")
            return nil
        }
        
        let order = AccountBean(dict: dict as! [String : String])
        return order
    }
    
    private func init_data() -> Void {
        guard let userid = UserDefaults.standard.value(forKey: SP_USERID) else {
            return
        }
        // 拼接数据
        let dict = NSMutableDictionary()
        dict.setValue(userid, forKey: SP_USERID)
        // 请求
        self.doPost(api: "search/linkman", dict: dict) { (dict) in
            if self.isServerSuccess(dict: dict) != 1200 {
                return
            }
            var temp = [AccountBean]()
            let arrs = dict.value(forKey: SP_BODYREQUEST) as! NSArray
            for item in arrs {
                let info = AccountBean(dict: item as! [String : Any])
                temp.append(info)
            }
            self.tempLinkman = temp
            self.accountView.accountBeans = temp
        }
    }
    
    private func init_view() -> Void {
        view.addSubview(backroundWhite)
        view.addSubview(accountView)
        view.addSubview(cirleAddView)
    }
}
